<?php
namespace App\Http\Controllers\desktop\publics;

use App\Models\Book;
use App\Models\Section;

class BookController extends BaseController {
	
	public function show($id) {
		$book = Book::find($id);
		if(is_null($book)) {
			return redirect('/404');
		}
		$book->clicks = ($book->clicks + 1);
		$book->save();
		$category = $book->category;
		$sections = $book->sections()->select(['id', 'name', 'order'])
				->orderBy('order')
				->paginate(300);
		$newSections = $book->sections()->select(['id', 'name', 'order'])
				->orderBy('order', 'desc')->take(9)->get();
		return view('desktop.publics.book', compact('book', 'sections', 'category', 'newSections'));
	}
	
	public function download($id) {
		$book = Book::find($id);
		if(is_null($book)) {
			return redirect('/404');
		}
		$hasTxt = file_exists(base_path('public/downloads/txt/'.$book->id.'.txt'));
		if(!$hasTxt) {
			$sections = Section::select(['id', 'name', 'content'])
					->where('book_id', $book->id)
					->orderBy('order', 'asc')
					->get();
			$data = "《".$book->name."》 \n";
			$data .= "简介：\n".strip_tags(str_replace('&nbsp;', '', $book->abstract));
			foreach ($sections as $section) {
				$data .= "\n".$section->name."\n";
				$data .= strip_tags(
						str_replace('<p>', '', 
								str_replace('</p>', " \n ", 
										str_replace('&emsp;', '', 
												str_replace('<br />', " \n ", 
														str_replace('&nbsp;', '', $section->content)
														)
												)
										)
								)
						);
			}
			file_put_contents(base_path('public/downloads/txt/'.$book->id.'.txt'), $data);
		}
		$book->downloads = ($book->downloads +1);
		$book->save();
		return response()->download(base_path('public/downloads/txt/'.$book->id.'.txt'), $book->name.'.txt');
	}
}
